/* eslint-disable react/no-access-state-in-setstate */
/* eslint-disable react/sort-comp */
/* eslint-disable react/jsx-no-bind */
/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 新零售的角色分配
 */
import React, { PureComponent, Fragment } from 'react';
import { Modal, Table, Checkbox, message } from 'antd';
import { connect } from 'dva';
import { config } from '@/components/_utils';

const { auths } = config;

@connect(({ loading, user }) => ({
  userInfo: user.currentUser,
  assigning: loading.effects['accounts/assign'],
}))
class Role extends PureComponent {
  constructor() {
    super();
    this.state = {
      visible: false,
      dataSource: [],
    };
    this.columns = [
      {
        title: '角色名称',
        dataIndex: 'name',
        key: 'name',
        render: (value, record) => {
          const { key, checked } = record;
          return (
            <Checkbox value={key} checked={checked} onChange={this.handleChange.bind(this)}>
              {value}
              管理员
            </Checkbox>
          );
        },
      },
      {
        title: '角色说明',
        dataIndex: 'desc',
        key: 'desc',
      },
    ];
  }

  // 切换选择
  handleChange(e) {
    const { value } = e.target;
    if (value === 'alls') {
      this.updateDataSource();
    } else {
      const dataSource = [...this.state.dataSource];
      const checkedList = [];
      dataSource.forEach(item => {
        const { key, checked } = item;
        if (key === value) {
          if (!checked) {
            checkedList.push(key);
          }
        } else if (checked && key !== 'alls') {
          checkedList.push(key);
        }
      });
      this.updateDataSource(checkedList);
    }
  }

  componentDidMount() {
    this.createTableData();
  }

  updateDataSource(checked = []) {
    if (!checked) return;
    const checkedList = checked.length === 0 ? ['alls'] : checked;
    const dataSource = [...this.state.dataSource];
    dataSource.forEach(item => {
      const { key, type } = item;
      if (checkedList.includes(key) || checkedList.includes(type)) {
        item.checked = true;
      } else {
        item.checked = false;
      }
    });
    this.setState({
      dataSource,
    });
  }

  // 创建已开启权限数据列表
  createTableData() {
    const { userInfo } = this.props;
    const { opened = [] } = userInfo || {};
    const list = [
      'alls',
      'finance',
      'system',
      ...(opened.length === 0
        ? ['business', 'delivery', 'orders', 'post', 'platform', 'allocation', 'auto']
        : opened),
    ];
    const dataSource = [];
    auths.forEach(item => {
      if (list.includes(item.key)) {
        dataSource.push({
          ...item,
        });
      }
    });
    this.setState({ dataSource });
  }

  // 打开权限设置弹窗
  handleClick() {
    this.setState(
      {
        visible: true,
      },
      this.updateDataSource.bind(this, this.props.checked),
    );
  }

  handleCancel() {
    this.setState({
      visible: false,
    });
  }

  handleOk() {
    const { dispatch, onAssigned, ids } = this.props;
    const { dataSource } = this.state;
    const checkedList = [];
    let hasCheck = false;
    dataSource.forEach(item => {
      const { checked } = item;
      if (checked) {
        hasCheck = true;
        checkedList.push(item);
      }
    });
    if (!hasCheck) {
      message.error('请先勾选要分配的角色');
      return;
    }
    dispatch({
      type: 'accounts/assign',
      payload: {
        id: ids,
        privilege: checkedList,
      },
      then: () => {
        this.handleCancel();
        onAssigned(checkedList);
      },
    });
  }

  render() {
    const { assigning } = this.props;
    const { visible, dataSource } = this.state;
    return (
      <Fragment>
        <span onClick={this.handleClick.bind(this)}>{this.props.children}</span>
        <Modal
          width={545}
          centered
          title="分配角色"
          visible={visible}
          onCancel={this.handleCancel.bind(this)}
          onOk={this.handleOk.bind(this)}
          okButtonProps={{ loading: assigning }}
        >
          <Table pagination={false} size="small" dataSource={dataSource} columns={this.columns} />
        </Modal>
      </Fragment>
    );
  }
}

Role.defaultProps = { ids: [], checked: null, onAssigned: () => {} };

Role.auths = auths;

export default Role;
